import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
// import { getOnlineLogsList } from "@/apiOld/system";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { callOrder_listByMerchant,outbound_list,crmuser_list } from "@/api/outbound"

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_outboundTask_add: false, // 外呼任务添加

    is_search_name: false, // 搜索名称
    is_search_status: false, // 搜索状态

    is_single_watch: false, // 监控
    is_single_recycle: false, // 回收未接
    is_single_pause: false, // 暂停
    is_single_excute: false, // 开始
    is_single_delete: false, // 删除

    is_batch_delete: false, // 批量删除
    is_batch_recycle: false, // 批量回收未接
  })

  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const form = reactive({
    orderType:"outboundCall",
    project: "",
    task: "",
    time: "",
    status: "",
    agentKey: "",
    phone: "",
    second: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const caseMap={
    "NORMAL_CLEARING":"正常挂断",
    "ORIGINATOR_CANCEL":"主叫挂机",
    "MEDIA_TIMEOUT":"呼叫超时",
    "USER_BUSY":"用户忙",
    "CALL_REJECTED":"拒绝呼叫",
    "NO_ANSWER":"无应答",
    "UNALLOCATED_NUMBER":"空号",
    "NO_USER_RESPONSE":"久叫不应",
    "USER_NOT_REGISTERED":"用户未注册",
    "NO_ROUTE_DESTINATION":"无法路由",
    "NETWORK_OUT_OF_ORDER":"网络异常",
    "NORMAL_UNSPECIFIED":"未定义",
    "RECOVERY_ON_TIMER_EXPIRE":"呼叫超时",
    "INCOMPATIBLE_DESTINATION":"目的地不兼容",
    "NORMAL_TEMPORARY_FAILURE":"临时故障",
    "DESTINATION_OUT_OF_ORDER":"目的地异常"
  }
  const answerFlagMap={
    0:'接通',
    1:'坐席未接用户未接',
    2:'坐席接通用户未接通',
    3:'用户接通坐席未接通'
  }
  const columns: TableColumnList = [
    {
      label: "主叫号码",
      prop: "caller",
      minWidth: 100
    },
    {
      label: "外显号码",
      prop: "callerDisplay",
      minWidth: 120
    },
    {
      label: "被叫号码",
      prop: "called",
      minWidth: 120
    },
    {
      label: "归属地",
      prop: "numberArea",
      minWidth: 150
    },
    {
      label: "坐席",
      prop: "agentName",
      minWidth: 150
    },
    {
      label: "拨打时间",
      prop: "callTime",
      minWidth: 200,
      formatter: ({ callTime }) =>
        dayjs(callTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "应答时长（秒）",
      prop: "talkTime",
      minWidth: 120,
      formatter: ({ talkTime }) =>{
          if(talkTime==0){
            return 0;
          }else{
            return Math.floor(talkTime/1000);
          }
      }
    },
    {
      label: "呼叫结果",
      prop: "answerFlag",
      minWidth: 200,
      formatter: ({ answerFlag }) =>{
        return answerFlagMap[answerFlag];
      }
    },
    {
      label: "客户状态",
      prop: "intention",
      minWidth: 130,
      formatter: ({ intention }) =>{
        let map={
          'unkown':'接通未确定',
          'refuse':'无意向',
          'intend':'有意向',
          '':'未确定'
        };
        return map[intention];
      }
    },
    {
      label: "领取状态",
      prop: "ext1",
      minWidth: 150,
      formatter: ({ ext1 }) =>{
        let map={
          'gain':'已领取',
          '':'未领取'
        };
        return map[ext1];
      }
    },
    {
      label: "挂断原因",
      prop: "hangupCause",
      minWidth: 150,
      formatter: ({ hangupCause}) =>{
        return caseMap[hangupCause];
      }
    },
    {
      label: "挂断处理",
      prop: "hangupDir",
      minWidth: 150,
      cellRenderer: ({ row, index }) => (
        <>
          {row.hangupDir == 1 ? "主叫挂机" : row.hangupDir == 2 ? "被叫挂机" : row.hangupDir == 3 ? "系统挂机" : ""}
        </>
      )
    },
    {
      label: "通话录音",
      // prop: "record",
      slot: "record",
      minWidth: 200,
    },
  ];


  function handleSizeChange(val: number) {
    pagination.pageSize = val
    dataList.value = []
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    dataList.value = []
    onSearch(); // 刷新表格数据
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getOnlineLogsList(toRaw(form));
    // dataList.value = data.list;
    // pagination.total = data.total;
    // pagination.pageSize = data.pageSize;
    // pagination.currentPage = data.currentPage;

    callOrder_listByMerchant({
      orderType:"autoOutboundCall",
      page:pagination.currentPage,
      size: pagination.pageSize,
      task_id:form.task,
      rangeTime:form.time.toString(),
      agentKey:form.agentKey,
      phone:form.phone,
      status:form.status,
      sort:"talk_time"
    }).then(res=>{
      if(res.code == 1000){
        dataList.value = res.data.list
        pagination.total =  res.data.total
        loading.value = false;
      }
    })
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.agentKey = ""
    onSearch();
  };

  const taskList = ref([])
  /** 获取群呼任务 */
  function getCallTask(){
    outbound_list().then(res=>{
      if(res.code == 1000){
        taskList.value = res.data.list
      }
    })
  }
  // 查询坐席列表
  const SeatsList = ref([])
  function getSeatsList(){
    crmuser_list().then(res=>{
      if(res.code == 1000){
        SeatsList.value = res.data.list
      }
    })
  }

  onMounted(() => {
    onSearch();
    getCallTask()
    getSeatsList()

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/groupcallManagement/task/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/groupcallManagement/task/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // outboundTask_add
      if (homeDataObj.outboundTask_add) permissions.is_outboundTask_add = true
      // outboundTask_list
      if (homeDataObj.outboundTask_list) {
        // search
        if (homeDataObj.outboundTask_list.search && homeDataObj.outboundTask_list.search.length) {
          let permiss = homeDataObj.outboundTask_list.search.join(',')
          permissions.is_search_name = permiss.includes('name') ? true : false
          permissions.is_search_status = permiss.includes('status') ? true : false
        }
        // single
        if (homeDataObj.outboundTask_list.single && homeDataObj.outboundTask_list.single.length) {
          let permiss = homeDataObj.outboundTask_list.single.join(',')
          permissions.is_single_watch = permiss.includes('watch') ? true : false
          permissions.is_single_recycle = permiss.includes('recycle') ? true : false
          permissions.is_single_pause = permiss.includes('pause') ? true : false
          permissions.is_single_excute = permiss.includes('excute') ? true : false
          permissions.is_single_delete = permiss.includes('delete') ? true : false
        }
        // batch
        if (homeDataObj.outboundTask_list.batch && homeDataObj.outboundTask_list.batch.length) {
          let permiss = homeDataObj.outboundTask_list.batch.join(',')
          permissions.is_batch_delete = permiss.includes('delete') ? true : false
          permissions.is_batch_recycle = permiss.includes('recycle') ? true : false
        }

        let tableRemove = homeDataObj.outboundTask_list.remove ? homeDataObj.outboundTask_list.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  return {
    shortcuts,
    form,
    loading,
    columns,
    dataList,
    pagination,
    taskList,
    SeatsList,
    onSearch,
    resetForm,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
  };
}
